package com.sskj.gcc.ui.fragment;


import android.graphics.Color;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.github.tifezh.kchartlib.chart.BaseKChartAdapter;
import com.github.tifezh.kchartlib.chart.KChartView;
import com.github.tifezh.kchartlib.chart.formatter.DateLFormatter;
import com.github.tifezh.kchartlib.chart.formatter.TimeFormatter;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.NumberUtil;
import com.sskj.common.util.TimeFormatUtil;
import com.sskj.gcc.R;
import com.sskj.gcc.bean.Stock;
import com.sskj.gcc.presenter.ChartFragmentPresenter;
import com.sskj.gcc.util.DataUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

@Deprecated
@Route(path = RConfig.APP_FRAGMENT_CHART)
public class ChartFragment extends BaseFragment<ChartFragmentPresenter> {
    @Override
    protected int getLayoutId() {
        return R.layout.app_fragment_chart;
    }

    @Override
    public ChartFragmentPresenter getPresenter() {
        return new ChartFragmentPresenter();
    }

    @BindView(R.id.kChartView)
    KChartView kChartView;
    private KChartAdapter mAdapter;
    @Autowired
    String code;
    @Autowired
    String goodType;
    @Autowired
    boolean isCandle = true;

    public KChartView getKChartView() {
        return kChartView;
    }


    @Override
    public void initView() {
        RxBus.getDefault().register(this);
        ARouter.getInstance().inject(this);
        kChartView.showLoading();
//        kChartView.setMainDownColor(R.color.app_999);
        kChartView.setVolumeMaGone(true);
        kChartView.setDrawTabView(false);
        kChartView.setGridRows(3);
        kChartView.setRedUpAndGreenDown(false);
//        kChartView.setGridLineColor(Color.parseColor("#e8e8e8"));
//        kChartView.setGridLineWidth(1f);
//        kChartView.setTextColor(Color.parseColor("#999999"));
//        ((MainDraw) kChartView.getMainDraw()).setSelectorTextColor(Color.WHITE);
        kChartView.setGridColumns(2);
        kChartView.setMinuteLineWidth(4);
//        kChartView.setBreathColor(Color.parseColor("#e83030"));
//        kChartView.setShader(Color.parseColor("#a07694BE"), Color.parseColor("#607694BE"), Color.parseColor("#207694BE"), 700);
        kChartView.setShader(Color.parseColor("#222C36"), Color.parseColor("#1C232B"), Color.parseColor("#192028"), 700);
        kChartView.setValueFormatter(v -> {
            if (code.toUpperCase().contains("USDT")) {
                return NumberUtil.keepMax(v, 4);
            } else {
                return NumberUtil.keepMax(v, 8);

            }
        });
        if (!isCandle) {
            kChartView.setDrawMinuteStyle(true);
            kChartView.setDateTimeFormatter(new TimeFormatter());
        } else {
            kChartView.setDateTimeFormatter(new DateLFormatter());
        }
        mAdapter = new KChartAdapter();
        kChartView.setAdapter(mAdapter);
        mPresenter.getKData(goodType, code);
    }


    public void setChart(List<Stock> stockList) {

        if (kChartView != null) {
            kChartView.hideLoading();
            if (stockList == null)
                return;
            Collections.reverse(stockList);
            DataUtil.calculate(stockList);
            mAdapter.getDatas().clear();
            mAdapter.updateData(stockList);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(this);
    }

    /**
     * 长链接  更新当前分时图
     *
     * @param
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void upDate(CoinBean data) {
        if (data.getCode().equals(code) && mAdapter.getCount() > 0) {
            if (isLastNewData(data)) {
                mAdapter.changeLastItemClosePrice(new BigDecimal(data.getPrice()).floatValue());
            } else {
                mPresenter.getKData(goodType, code);
            }

        }


    }

    private boolean isLastNewData(CoinBean data) {
        try {
            String time = data.getDate() + " " + data.getTime();
            Date newDate = TimeFormatUtil.SF_FORMAT_E.parse(time);
            long compareTime = newDate.getTime();
            return isSameTime(compareTime);
        } catch (ParseException e) {
            return false;
        }
    }

    private boolean isSameTime(long compareTime) {
        long dividerTime = 1;
        switch (goodType) {
            case "minute":
                dividerTime = 1000 * 60;
                break;
            case "minute15":
                dividerTime = 1000 * 60 * 15;
                break;
            case "minute30":
                dividerTime = 1000 * 60 * 30;
                break;
            case "minute60":
                dividerTime = 1000 * 60 * 60;
                break;
            case "day":
                dividerTime = 1000 * 60 * 60 * 24;
                break;
        }
        return compareTime / dividerTime == mAdapter.getDatas().get(mAdapter.getCount() - 1).getDate() / dividerTime;
    }

    /**
     * 数据适配器
     * Created by tifezh on 2016/6/18.
     */

    public class KChartAdapter extends BaseKChartAdapter {

        private List<Stock> datas = new ArrayList<>();

        public KChartAdapter() {

        }

        public List<Stock> getDatas() {
            return datas;
        }

        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public Object getItem(int position) {
            return datas.get(position);
        }

        @Override
        public Date getDate(int position) {
            return new Date(datas.get(position).getDate());
        }

        /**
         * 向头部添加数据
         */
        public void addNewData(List<Stock> data) {
            if (data != null && !data.isEmpty()) {
                datas.addAll(data);
                notifyItemRangeInsertedToLast();
            }
        }


        /**
         * 向尾部添加数据
         */
        public void updateData(List<Stock> data) {
            if (data != null && !data.isEmpty()) {
                datas.clear();
                datas.addAll(0, data);
                notifyDataSetChanged();
            }
        }

        /**
         * 改变某个点的值
         */
        public void changeLastItemClosePrice(float closePrice) {
            notifyLastItemChanged(closePrice);
        }

    }
}
